package com.sinaapp.gavinzhang.ConcurrentProgramming;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * synchronized对非静态方法的锁是对该对象的锁
 * Created by gavin on 15-9-1.
 */
public class SynchronizedTest {
    public static void main(String[] args)
    {
        Account account = new Account();
        account.setMoney(1000);
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        threadPool.execute(new Company(account));
        threadPool.execute(new Bank(account));
        while (true){
            System.out.println(account.getMoney());
            if (account.getMoney()==1000)break;
        }
        threadPool.shutdown();
        System.out.println(account.getMoney());
    }
}

class Company implements Runnable{
    private Account account;

    public Company(Account account) {
        this.account = account;
    }

    public void run() {
        for (int i = 0; i < 100; i++) {
            account.add(100);
        }
    }
}

class Bank implements Runnable{
    private Account account;

    public Bank(Account account) {
        this.account = account;
    }

    public void run() {
        for (int i = 0; i < 100; i++) {
            account.subtract(100);
        }
    }
}

class Account{
    private int money;

    synchronized public int add(int money)
    {
        this.money += money;
        return this.money;
    }

    synchronized public int subtract(int money)
    {
        this.money -= money;
        return this.money;
    }


    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}
